﻿using Autofac;
using Autofac.Integration.Mvc;
using System;
using System.IO;
using System.Reflection;
using System.Web.Mvc;
using Shake.Framework.Interceptors;
using Shake.Framework.Utility;

namespace Shake.Web
{
    public class AutofacConfig
    {
        public static void Register()
        {
            var builder = new ContainerBuilder();
            CacheConfig.Register(builder);
            RegistShakeFramework(builder);
            RegisterBusiness(builder);
            builder.Register(t => new CacheInterceptor());
            builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); ;
            Shake.Framework.Setup.AutofacConfig.Container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(Shake.Framework.Setup.AutofacConfig.Container));
        }

        private static void RegistShakeFramework(ContainerBuilder builder)
        {
            // 注册主项目下的framework
            var frameworkAssembly = Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin/Shake.Framework.dll"));
            //builder.RegisterAssemblyTypes(frameworkAssembly).AsImplementedInterfaces().InstancePerLifetimeScope().EnableInterfaceInterceptors().InterceptedBy(typeof(CacheInterceptor));
            builder.RegisterAssemblyTypes(frameworkAssembly).AsImplementedInterfaces().InstancePerLifetimeScope().PropertiesAutowired();
        }

        private static void RegisterBusiness(ContainerBuilder builder)
        {
            var assembly = Shake.Business.Register.GetAssembly();
            builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces().InstancePerLifetimeScope().PropertiesAutowired();
            //builder.RegisterControllers(assembly).PropertiesAutowired();
        }
    }
}